#include "_SPI_.h"

void HSPI_Init(SPI_TypeDef* SPIx){
	 	GPIO_InitTypeDef GPIO_InitStructure;
  	SPI_InitTypeDef  SPI_InitStructure;

	if(SPIx==SPI1){RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1,  ENABLE );RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);}
	else if(SPIx==SPI2){RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2,  ENABLE );RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);}

	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	if(SPIx==SPI1){
		GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;
		GPIO_Init(GPIOA, &GPIO_InitStructure);
 		GPIO_SetBits(GPIOA,GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7);//init gpio pin status
	}
	else if(SPIx==SPI2){
		GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;
		GPIO_Init(GPIOB, &GPIO_InitStructure);
 		GPIO_SetBits(GPIOB,GPIO_Pin_13|GPIO_Pin_14|GPIO_Pin_15);//init gpio pin status
	}

	SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;  //SPI设置为双线双向全双工
	SPI_InitStructure.SPI_Mode = SPI_Mode_Master;		//SPI主机
  SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;		//发送接收8位帧结构
	SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;		//时钟悬空低
	SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;	//数据捕获于第1个时钟沿
	SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;		//NSS信号由软件控制
	SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;		//定义波特率预分频的值:波特率预分频值为16
	SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;	//数据传输从MSB位开始
	SPI_InitStructure.SPI_CRCPolynomial = 7;	//CRC值计算的多项式
	SPI_Init(SPIx, &SPI_InitStructure);  //根据SPI_InitStruct中指定的参数初始化外设SPIx寄存器

	SPI_Cmd(SPIx, ENABLE);
	HSPI_ReadWriteByte(0xffff);//clear data
}

uint16_t HSPI_ReadWriteByte(uint16_t Data){
	uint8_t retrun_time=0;//we set a wait time here ,if we have get right flag,we will return 0 ，设置超时时间，如果话没有接受到信号，直接返回0，防止程序卡死
	while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) != SET&&retrun_time<=2000)retrun_time++;
	SPI_I2S_SendData(SPI2, Data);
	retrun_time=0;
	while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) != SET&&retrun_time<=2000)retrun_time++;
	return SPI_I2S_ReceiveData(SPI2);
}

void SPI_SetSpeed(uint8_t SPI_BaudRatePrescaler){
  	assert_param(IS_SPI_BAUDRATE_PRESCALER(SPI_BaudRatePrescaler));
	SPI2->CR1&=0XFFC7;
	SPI2->CR1|=SPI_BaudRatePrescaler;
	SPI_Cmd(SPI2,ENABLE);
}

